#netblast_info.pl
#author: Jeremy Cothran (jeremy.cothran@gmail.com)
#date: March 28, 2008

use strict;
use DBI;

###config
my $path_blast = 'C:\\Docume~1\\logan\\Desktop\\joe_jones\\blast\\blastcl3.exe';
my $dbname = 'thermus_run1.db';
###

my $dbh = DBI->connect("dbi:SQLite:dbname=$dbname", "", "",
                    { RaiseError => 1, AutoCommit => 1 });
if(!defined $dbh) {die "Cannot connect to database!\n";}
my ($sql,$sth);

my ($query_file,$query_file_out) = @ARGV;

if (@ARGV < 2) { print "usage like : perl netblast_info.pl found/summary_unique_found.txt query_out.txt \n"; exit 0; }


open (FILE_QUERY,"$query_file");
open (FILE_QUERY_OUT,">$query_file_out");

my $line;
while ($line = <FILE_QUERY>) {

if (($line =~ /^>/) || ($line =~ /^#/)) {
	print FILE_QUERY_OUT "$line";
	next;

}

my ($count,$seq) = split(/\s+/,$line);

print "analysis $count $seq\n";
print FILE_QUERY_OUT "analysis $count $seq\n";

#############################
#try database lookup first

$sql = qq{ SELECT lkp_string from netblast_lkp where sequence = '$seq' };
#print $sql."\n";
$sth = $dbh->prepare( $sql );
$sth->execute();
my ($lkp_string) = $sth->fetchrow_array;

if ($lkp_string) { print FILE_QUERY_OUT $lkp_string; }

#############################
else { #else try netblast lookup

my $query_out_string = '';

open (FILE_TEMP,">temp.txt");
print FILE_TEMP $seq;
close FILE_TEMP;

#get identity info
#need some error checking below on blast run
my $identity = `$path_blast -p blastn -d nr -m 1 -v 1 -b 1 < temp.txt`;

my @array_identity = split(/\n/,$identity);

foreach my $line_identity (@array_identity) {
	if ($line_identity =~ m/\|.*\|/ ) {
		$query_out_string .= "identity $line_identity\n";
	}
}

#get alignment info
#need some error checking below on blast run
my $analysis = `$path_blast -p blastn -d nr -m 8 -v 1 -b 1 < temp.txt`;

$query_out_string .= $analysis;

$sql = qq{ INSERT into netblast_lkp(row_entry_date,sequence,lkp_string) values (datetime('now'),'$seq','$query_out_string') };
#print $sql."\n";
$sth = $dbh->prepare( $sql );
$sth->execute();

print FILE_QUERY_OUT $query_out_string;

} #else netblast lookup
} #while file lines

#database cleanup - may not be as necessary for sqlite, but safer
$sth->finish();
undef $sth; # to stop "closing dbh with active statement handles"
            # http://rt.cpan.org/Ticket/Display.html?id=22688
$dbh->disconnect();

exit 0;